package com.wwc.bwcj.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.wwc.bwcj.activity.MainActivity
import com.wwc.bwcj.R
import com.wwc.bwcj.activity.RegisterActivity

class LoginActivity : AppCompatActivity() {
    private lateinit var etUserName: EditText
    private lateinit var etPassword: EditText
    private lateinit var btnLogin: Button
    private lateinit var tvRegister: TextView

    // 定义本地预设的账号密码
    private val VALID_USERNAME = "admin"
    private val VALID_PASSWORD = "123456"

    companion object {
        // 用于存储注册用户账号密码的Map
        val registeredUsers = mutableMapOf<String, String>()
    }

    /**
     * 页面初始化
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_login)

        //初始化UI组件引用
        etUserName = findViewById(R.id.et_user_name)
        etPassword = findViewById(R.id.et_password)
        btnLogin = findViewById(R.id.btn_login)
        tvRegister = findViewById(R.id.tv_register)

        btnLogin.setOnClickListener {
            login()
        }

        tvRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    /**
     * 登录方法
     */
    private fun login() {
        val userName = etUserName.text.toString().trim()
        val password = etPassword.text.toString().trim()

        // 先进行判空
        if (userName.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名/密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        // 比对账号密码是否正确
        // 首先检查是否是预设账号
        if (userName == VALID_USERNAME && password == VALID_PASSWORD) {
            // 登录成功，保存登录状态
            saveLoginStatus(userName)
            navigateToMain()
            return
        }

        // 然后检查是否是注册用户
        if (registeredUsers.containsKey(userName) && registeredUsers[userName] == password) {
            // 登录成功，保存登录状态
            saveLoginStatus(userName)
            navigateToMain()
            return
        }

        // 登录失败
        Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show()
    }

    private fun saveLoginStatus(userName: String) {
        getSharedPreferences("user_prefs", MODE_PRIVATE).edit()
            .putBoolean("isLogin", true)
            .putString("userName", userName)
            .apply()
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
    }

    /**
     * 登陆成功，页面跳转到主页面
     */
    private fun navigateToMain() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
}